package com.example.mycarcalling.controller;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import cn.hutool.system.SystemUtil;
import com.example.mycarcalling.utils.FileUtils;
import com.example.mycarcalling.utils.ResponseResult;
import com.example.mycarcalling.utils.UUIDUtils;
import com.example.mycarcalling.vo.ProgressEntity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;

@RestController
public class FileUploadController {

    private final Log log = LogFactory.get();
    /**
     * 配置的上传路径
     */
    @Value("${file.path}")
    private String filePath;

    @Value("${driverPicture.selectPath}")
    private String selectPath;

    /**
     * 普通文件上传
     *
     * @param driverPicture
     * @param request
     * @return
     */
    @PostMapping("/uploadFile")
    public ResponseResult uploadFile(@RequestParam("driverPicture") List<CommonsMultipartFile> driverPicture, HttpServletRequest request) {
        List<String> fileNameList = new ArrayList<>();
        boolean result = false;
        for (CommonsMultipartFile file : driverPicture) {
            //获取原文件名称和后缀
            try {
                // 获取文件后缀名
                String imgType = file.getOriginalFilename().substring(
                        file.getOriginalFilename().lastIndexOf(".") + 1);
                if (imgType.equals("")) {
                    throw new Exception("上传图片失败");
                }
                String fileName = UUIDUtils.getUUID() + "." + imgType;
                String path = StpUtil.getLoginIdAsLong() + "/" + fileName;

                File file1 = new File(filePath + path);
                boolean mkdirs = file1.mkdirs();
                log.info("文件夹{}创建{}", file1.getAbsolutePath(), mkdirs ? "成功" : "失败");
                file.transferTo(file1);
                log.info("{} 上传成功！", fileName);
                fileNameList.add(fileName);
                result = true;

            } catch (NotLoginException e) {
                e.printStackTrace();
                return new ResponseResult(503, e.getMessage(), null);
            } catch (IOException e) {
                e.printStackTrace();

                log.error("{} 上传失败！", file);
                String relPath = filePath + "/" + StpUtil.getLoginIdAsLong();
                FileUtils.deleteDirectory(relPath);
                break;

            } catch (Exception e) {
                e.printStackTrace();
                return new ResponseResult(500, e.getMessage(), null);
            }

        }
        if (result) {
            return new ResponseResult(200, "success", fileNameList);
        }else {
            return new ResponseResult(500, "failed", null);
        }
    }
    /**
     * 获取上传进度
     *
     * @param request
     * @return
     */
    @GetMapping(value = "/uploadStatus")
    public ResponseResult uploadStatus(HttpServletRequest request) {
        try {
            HttpSession session = request.getSession();
            ProgressEntity percent = (ProgressEntity) session.getAttribute("status");
            return new ResponseResult(200, "success", percent);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseResult(500, "failed", null);
        }
    }

    /**
     * 显示图片
     * @return
     */
    @RequestMapping(value="/viewPhoto/{photoPath}")
    public void getFeedBackPicture(HttpServletResponse response, @PathVariable("photoPath") String photoPath) throws Exception{
        String realPath= selectPath +"/"+ StpUtil.getLoginIdAsLong() +"/" +photoPath;
        FileInputStream inputStream = new FileInputStream(realPath);
        int i = inputStream.available();
        //byte数组用于存放图片字节数据
        byte[] buff = new byte[i];
        inputStream.read(buff);
        //关闭输入流
        inputStream.close();
        //设置发送到客户端的响应内容类型
        response.setContentType("image/*");
        OutputStream out = response.getOutputStream();
        out.write(buff);
        //关闭响应输出流
        out.close();
    }


    /**
     * 删除文件
     * @return
     */
    @GetMapping(value = "/deleteFile")
    public ResponseResult deleteFile() {
        try {

            String relPath = filePath + "/" + StpUtil.getLoginIdAsLong();

            boolean result =  FileUtils.deleteDirectory(relPath);
            if(result){
                return new ResponseResult(200,"success",null);
            }
            throw new Exception("删除失败");

        }catch (NotLoginException e){
            e.printStackTrace();
            return new ResponseResult(503,e.getMessage(),null);
        } catch (Exception e){
            e.printStackTrace();
            return new ResponseResult(500,e.getMessage(),null);
        }
    }
}
